import { apiService } from './api'
import { API_ENDPOINTS } from '@/config/api'

// 登录请求接口
export interface LoginRequest {
  username: string
  password: string
}

// 登录响应接口
export interface LoginResponse {
  token: string
  username: string
  expires_at: number
}

// 用户信息接口
export interface UserInfo {
  username: string
  token: string
  expires_at: number
}

// Token存储key
const TOKEN_KEY = 'ota_token'
const USER_INFO_KEY = 'ota_user_info'

// 认证服务
export const authService = {
  // 登录
  login: async (loginData: LoginRequest): Promise<LoginResponse> => {
    const response = await apiService.post<LoginResponse>(API_ENDPOINTS.AUTH_LOGIN, loginData)
    
    // 保存token和用户信息到localStorage
    localStorage.setItem(TOKEN_KEY, response.token)
    localStorage.setItem(USER_INFO_KEY, JSON.stringify({
      username: response.username,
      token: response.token,
      expires_at: response.expires_at
    }))
    
    return response
  },

  // 登出
  logout: () => {
    localStorage.removeItem(TOKEN_KEY)
    localStorage.removeItem(USER_INFO_KEY)
  },

  // 获取token
  getToken: (): string | null => {
    return localStorage.getItem(TOKEN_KEY)
  },

  // 获取用户信息
  getUserInfo: (): UserInfo | null => {
    const userInfoStr = localStorage.getItem(USER_INFO_KEY)
    if (userInfoStr) {
      try {
        return JSON.parse(userInfoStr)
      } catch {
        return null
      }
    }
    return null
  },

  // 检查是否已登录
  isAuthenticated: (): boolean => {
    const token = authService.getToken()
    const userInfo = authService.getUserInfo()
    
    if (!token || !userInfo) {
      return false
    }
    
    // 检查token是否过期
    const now = Math.floor(Date.now() / 1000)
    if (userInfo.expires_at <= now) {
      authService.logout()
      return false
    }
    
    return true
  },

  // 检查token是否即将过期（剩余时间小于1小时）
  isTokenExpiringSoon: (): boolean => {
    const userInfo = authService.getUserInfo()
    if (!userInfo) return false
    
    const now = Math.floor(Date.now() / 1000)
    const oneHour = 60 * 60
    return (userInfo.expires_at - now) < oneHour
  }
} 